<template>
	<div class="m-view-overCodeApply m-window">
		<!--查询条件-->
		<div class="m-condition">
			<el-row :gutter="10">
				<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="6">
						<el-form-item :label="accountType==1?'公司':'客户'" class="rightItem">
							<el-select
								v-model="searchForm.companyCode"
								placeholder="请选择"
								value-key="id"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="申请日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.applyStartDate"
								type="date"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								clearable
								:editable="false"
								:picker-options="pickerStart_option"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="searchForm.applyEndDate"
							type="date"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							clearable
							:editable="false"
							:picker-options="pickerEnd_option"
						></el-date-picker>
					</el-col>
					<el-col :span="5">
						<el-form-item label="审核日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.auditDateStart"
								type="date"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								clearable
								:editable="false"
								:picker-options="pickerStart_option"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="searchForm.auditDateEnd"
							type="date"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							clearable
							:editable="false"
							:picker-options="pickerEnd_option"
						></el-date-picker>
					</el-col>
				</el-form>
			</el-row>
			<el-row :gutter="10">
				<el-form ref="ruleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="6" v-if="accountType==1">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="searchForm.supplierName"
								readonly
								clearable
								@focus="showSupplierDialog"
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave"
							>
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="单据状态" class="rightItem">
							<el-select
								v-model="searchForm.state"
								placeholder="单据状态"
								value-key="value"
								@change="stateChange"
							>
								<el-option
									v-for="item in stateOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-form>
				<el-col :span="2" class="m-floatright" v-if="searchForm.state==3">
					<el-button type="primary" @click="getBarcodesList">条码清单</el-button>
				</el-col>
				<el-col
					:span="2"
					class="m-floatright"
					v-if="accountType==4&&searchForm.state==0||searchForm.state==2"
				>
					<el-button type="primary" @click="deletedData">删除</el-button>
				</el-col>
				<el-col
					:span="2"
					class="m-floatright"
					v-if="accountType==4&&searchForm.state==0||searchForm.state==2"
				>
					<el-button type="primary" @click="edit('edit')">编辑</el-button>
				</el-col>
				<el-col :span="2" class="m-floatright" v-if="accountType==1&&searchForm.state<3">
					<el-button type="primary" @click="edit('audit')">审核</el-button>
				</el-col>
				<el-col :span="2" class="m-floatright">
					<el-button type="primary" @click="edit('view')">查看</el-button>
				</el-col>
				<el-col :span="2" class="m-floatright">
					<el-button type="primary" @click="search(1)">查询</el-button>
				</el-col>
			</el-row>
		</div>
		<!--加码申请列表-->
		<div class="m-agTable m-top2 m-bottom">
			<agGridComponents
				ref="agGridComponent"
				:getColumnDefs="columnDefs"
				:getRowSelection="'multiple'"
				:getGridOptions="gridOptions"
				:isColFit="true"
			></agGridComponents>
		</div>
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 供应商信息弹窗 -->
		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<srmSupplierInfo
				ref="srmSupplierInfo"
				:layout="searchForm"
				@setSrmSupplierInfo="setSrmSupplierInfo"
			></srmSupplierInfo>
		</el-dialog>
		<!-- 编辑或审核或查看界面 -->
		<overCodeDialog
			:editModel="editModel"
			:dialogVisible="dialogVisible"
			:ruleForm="materielInfo"
			:addedAmount="addedAmount"
			@closeDialog="closeDialog"
			ref="overCodeDialog"
		></overCodeDialog>
		<!-- 条码清单弹窗 -->
		<barCodeInfoDialog
			v-if="barCodeDialogVisible"
			:barCodeDialogVisible="barCodeDialogVisible"
			:isSmallCode="isSmallCode"
			:mainParams="mainParams"
			:delCodeShow="delCodeShow"
			:supplierInfo="supplierInfo"
			:showAddCodeCol="showAddCodeCol"
			@barCodeClose="barCodeDialogVisible=false"
		></barCodeInfoDialog>
	</div>
</template>

<script>
import srmSupplierInfo from "@/components/srmSupplierInfo"
import overCodeDialog from "./common/overCodeDialog"
import barCodeInfoDialog from "./common/barCodeInfoDialog"
import authInfo from "@/public/authInfo"
import subOperation from '@/public/addOperation'
import Msg from "@/public/message"
import gridOptions from 'lesso-common/public/gridOptions';
import agGridComponents from "@/components/agGridComponents"
export default {
	data () {
		return {
			// 日期控件配置
			pickerStart_option: {
				disabledDate: this.disabledDate1
			},
			//  日期控件配置  
			pickerEnd_option: {
				disabledDate: this.disabledDate2
			},
			// 查询条件
			searchForm: {
				companyCode: '',
				supplierName: '',
				supplierCode: '',
				applyStartDate: '',
				applyEndDate: '',
				orderNo: '',
				state: '',
				auth: true,
				auditDateStart: '',
				auditDateEnd: ''
			},
			// 分页相关信息
			pageInfo: {
				size: 30,
				current: 1,
				total: 0
			},
			// 表格配置项
			gridOptions: {},
			// 表格列配置
			columnDefs: [],
			// 公司或客户下拉菜单
			comOptions: [],
			//   单据状态下拉
			stateOptions: [
				{ label: '未审核', value: 1 },
				{ label: '已审核', value: 3 },
			],
			// 清除按钮是否显示
			inputClearBut: false,
			// 供应商选择弹窗是否显示   
			srmSupplierDialogVisible: false,
			//   合计申请数量
			totalApplyAmount: 0,
			// 审核类型
			accountType: this.$global.user.userTypeId,
			//   操作模式
			editModel: '',
			//  编辑或审核弹窗是否显示
			dialogVisible: false,
			// 加码物料信息  
			materielInfo: {
				purOrdNo: '',
				matName: '',
				orderAmount: '',
				genCodeAmount: '',
				canGenAmount: '',
				type: '1',
				model: '',
				labMatName: '',
				standard: '',
				productionArea: '',
				shelfLife: '',
				weight: '',
				productDate: '',
				batchCode: '',
				inspectionCode: '',
				amount: '',
				remark: ''
			},
			// 条码清单弹窗   
			barCodeDialogVisible: false,
			delCodeShow: false,
			mainParams: {
				data: {}
			},
			supplierInfo: [],
			isSmallCode: false,
			showAddCodeCol: false,
			addedAmount: 0
		}
	},
	props: {
	},
	methods: {
		// 开始日期不能大于结束日期
		disabledDate1 (time) {
			if (this.searchForm.applyEndDate)
				return time.getTime() > new Date(this.searchForm.applyEndDate).getTime();
		},
		// 结束日期不能小于开始日期
		disabledDate2 (time) {
			if (this.searchForm.applyStartDate)
				return time.getTime() < (new Date(this.searchForm.applyStartDate).getTime() - 3600 * 1000 * 24);
		},
		// 获取列表数据
		search (flag) {
			if (flag == 1) this.pageInfo.current = 1
			const { size, current } = this.pageInfo
			const { supplierCode, companyCode, applyStartDate, applyEndDate, state, auditDateStart, auditDateEnd } = this.searchForm
			let params = {
				currentPage: current,
				pageSize: size,
				billState: state,
				supplierCode: '',
				companyCode: companyCode,
				auditDateStart,
				auditDateEnd,
				createDateStart: applyStartDate,
				createDateEnd: applyEndDate,
			}
			this.totalApplyAmount = 0
			if (this.accountType == 4) {
				params.supplierCode = this.$global.supplierData.supplierCode
				if (!params.supplierCode) {
					Msg.showPopMsg('供应商编码不能为空')
					return
				}
			} else {
				params.supplierCode = supplierCode
			}
			this.$refs['agGridComponent'].loading = true
			this.$http.getApplyBarcodeList(params).then(({ data }) => {
				this.$refs['agGridComponent'].loading = false
				if (data.code == 1) {
					this.$refs['agGridComponent'].gridOptions.api.setRowData(data.rows)
					this.pageInfo.total = data.total
					data.rows.forEach(el => {
						this.totalApplyAmount = subOperation.accAdd(el.amount, this.totalApplyAmount)
					})
					this.$refs['agGridComponent'].gridOptions.api.setPinnedBottomRowData(this.createData(1, "Bottom"))
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.$refs['agGridComponent'].loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		stateChange () {
			this.search(1)
		},
		// 查看条码清单
		getBarcodesList () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length == 0) {
				Msg.showPopMsg(`请选择你要查看的条码清单`)
				return
			} else if (row.length > 1) {
				Msg.showPopMsg(`每次只能选择一条数据`)
				return
			}
			const { supplierCode, supplierName, type } = row[0]
			this.supplierInfo = [{
				supplierCode,
				supplierName
			}]
			this.mainParams.data = row[0]
			this.isSmallCode = type == 2 ? true : false
			if (this.isSmallCode) {
				this.mainParams.data.uniqueSmall = row[0].unique
			}
			this.barCodeDialogVisible = true
		},
		// 查看申请详情
		viewDetail () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length == 0) {
				Msg.showPopMsg(`请选择你要查看的数据`)
				return
			} else if (row.length > 1) {
				Msg.showPopMsg(`每次只能选择一条数据进行查看`)
				return
			}
			this.editModel = "查看"
			this.dialogVisible = true
		},
		// 编辑申请信息
		edit (type) {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			let text = type == 'audit' ? '审核' : type == 'edit' ? '编辑' : '查看'
			if (row.length == 0) {
				Msg.showPopMsg(`请选择你要${text}的数据`)
				return
			} else if (row.length > 1) {
				Msg.showPopMsg(`每次只能选择一条数据进行${text}`)
				return
			}
			const { id, purOrdNo, purOrdMxNo, matName, matCode } = row[0]
			this.materielInfo.purOrdNo = purOrdNo //订单号
			this.materielInfo.matName = matName //物料描述
			//   this.materielInfo.genCodeAmount = genCodeAmount //已生成数量
			//   this.materielInfo.canGenAmount = subOperation.accSub(orderAmount, genCodeAmount); //可生成数量
			this.materielInfo.purOrdMxNo = purOrdMxNo //订单行号
			this.materielInfo.matCode = matCode //物料编号
			this.materielInfo.id = id
			this.getBarCodeApplyDetail(row[0].id)
			this.editModel = type
			this.dialogVisible = true
		},
		closeDialog () {
			this.materielInfo = {
				purOrdNo: '',
				matName: '',
				orderAmount: '',
				genCodeAmount: '',
				canGenAmount: '',
				type: '1',
				model: '',
				labMatName: '',
				standard: '',
				productionArea: '',
				shelfLife: '',
				weight: '',
				productDate: '',
				batchCode: '',
				inspectionCode: '',
				amount: '',
				remark: '',
				auxAmount: ''
			}
			this.dialogVisible = false
			this.search(1)
		},
		// 获取加码申请详情信息
		getBarCodeApplyDetail (applyId) {
			this.$refs['overCodeDialog'].loading = true
			this.$http.getApplyBarcodeDetail({ id: applyId }).then(({ data }) => {
				this.$refs['overCodeDialog'].loading = false
				if (data.code == 1) {
					const {
						auxAmount,
						labMatName,
						model,
						productionArea,
						shelfLife,
						standard,
						weight,
						assistNum,
						orderAmount,
						level,
						type,
						genCodeAmount,
						jth, productDate, remark, batchCode, amount, inspectionCode, billState, excessLimit } = data.rows
					this.materielInfo.orderAmount = orderAmount// 订单数量
					let packageAmount = subOperation.accMul(orderAmount, auxAmount)// 包装数量
					let limitAmount = Math.round(subOperation.accMul(packageAmount, excessLimit)) //最大可申请加码数量,四舍五入取整 
					this.materielInfo.genCodeAmount = genCodeAmount //已加码数量
					this.materielInfo.canGenAmount = subOperation.accSub(limitAmount, this.materielInfo.genCodeAmount) //可加码数量
					this.materielInfo.labMatName = labMatName //物料名称
					this.materielInfo.model = model //型号
					this.materielInfo.productionArea = productionArea // 产地
					this.materielInfo.shelfLife = shelfLife //保质期
					this.materielInfo.standard = standard //执行标准
					this.materielInfo.weight = weight //重量
					this.materielInfo.assistNum = assistNum //辅数量
					this.materielInfo.level = level //层级
					this.materielInfo.jth = jth //机台号
					this.materielInfo.inspectionCode = inspectionCode //质检号
					this.materielInfo.amount = amount //生成数量
					this.materielInfo.productDate = productDate //生产日期
					this.materielInfo.remark = remark //原因
					this.materielInfo.batchCode = batchCode //生产批号
					this.materielInfo.type = type //条码类型
					this.materielInfo.billState = billState//单据状态
					this.materielInfo.auxAmount = auxAmount
					this.materielInfo.excessLimit = excessLimit
					this.addedAmount = amount - 0
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.$refs['overCodeDialog'].loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 删除数据
		deletedData () {
			let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows()
			if (row.length == 0) {
				Msg.showPopMsg(`请选择你要删除的数据`)
				return
			}
			let ids = row.map(el => {
				return el.id
			})
			let params = {
				idList: ids,
				modifyerId: this.$global.user.id,
				modifyer: this.$global.user.employeeName
			}
			this.$confirm("数据删除后将不可恢复，是否确认删除？", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				center: true,
				distinguishCancelAndClose: true,
				type: 'warning'
			}).then(_ => {
				this.$http.deletedBarcode(params).then(({ data }) => {
					if (data.code == 1) {
						Msg.showSuccessMsg('删除成功')
						this.search(1)
					} else {
						Msg.showErrorMsg(data.info)
					}
				}).catch(err => {
					Msg.showErrorMsg(err.data.message)
				})
			}).catch(_ => { })
		},
		// 分页相关回调
		handleSizeChange (val) {
			this.pageInfo.size = val
			this.pageInfo.current = 1
		},
		handleCurrentChange (val) {
			this.pageInfo.current = val
		},
		// 显示供应商选择框
		showSupplierDialog () {
			if (!this.searchForm.companyCode) {
				Msg.showPopMsg("提示：请选择公司！")
				this.$refs.content.focus()
				return
			} else {
				this.srmSupplierDialogVisible = true;
				this.$nextTick(_ => {
					this.$refs.srmSupplierInfo.search();
				})
			}
		},
		// 鼠标移出供应商选择框
		mounseLeave () {
			if (this.searchForm.supplierName != "")
				this.inputClearBut = false
		},
		// 鼠标移入供应商选择框
		mouseEnter () {
			if (this.searchForm.supplierName != "")
				this.inputClearBut = true
		},
		// 清除输入信息
		inputClearSon () {
			this.searchForm.supplierName = ''
			this.searchForm.supplierCode = ''
			this.inputClearBut = false
		},
		// 已选择供应商
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				this.srmSupplierDialogVisible = false
				this.searchForm.supplierCode = msg[0].supplierCode
				this.searchForm.supplierName = msg[0].supplierName
			}
		},
		// 关闭供应商选择弹窗
		srmSupplierDialogClose (done) {
			done()
		},
		// 获取公司下拉列表信息
		getAuthCompany () {
			authInfo.getAuthInfo().then((data) => {
				this.comOptions = data
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		// 创建底部合计栏
		createData (count) {
			let result = []
			for (let i = 0; i < count; i++) {
				result.push({
					matName: "合计",
					amount: this.totalApplyAmount,
				})
			}
			return result
		},
		// 获取物料详情
		// getMaterielInfo (codeType) {
		//   const { purOrdMxNo, purOrdNo, matCode } = this.materielInfo
		//   let params = {
		//     supplierCode: this.supplierInfo[0].supplierCode,
		//     type: codeType,
		//     purOrdMxNo,
		//     purOrdNo,
		//     matCode
		//   }
		//   this.$refs['overCodeDialog'].loading = true
		//   this.$http.applyCodeMaterielInfo(params).then(({ data }) => {
		//     this.$refs['overCodeDialog'].loading = false
		//     if (data.code == 1) {
		//       const { auxAmount, labMatName, model, productionArea, shelfLife, standard, weight, assistNum, level, jth } = data.rows
		//       this.materielInfo.labMatName = labMatName.auxAmount //物料名称
		//       this.materielInfo.model = model //型号
		//       this.materielInfo.productionArea = productionArea // 产地
		//       this.materielInfo.shelfLife = shelfLife //保质期
		//       this.materielInfo.standard = standard //执行标准
		//       this.materielInfo.weight = weight //重量
		//       this.materielInfo.assistNum = assistNum //辅数量
		//       this.materielInfo.level = level //层级
		//       this.materielInfo.jth = jth //机台号
		//       this.materielInfo.auxAmount = auxAmount
		//     } else {
		//       this.$refs['overCodeDialog'].resetForm()
		//       Msg.showErrorMsg(data.info)
		//     }
		//   }).catch(err => {
		//     this.$refs['overCodeDialog'].resetForm()
		//     this.$refs['overCodeDialog'].loading = false
		//     Msg.showErrorMsg(err.data.message)
		//   })
		// }
	},
	components: {
		srmSupplierInfo,
		overCodeDialog,
		barCodeInfoDialog,
		agGridComponents
	},
	beforeMount () {
		if (this.accountType == 1) {
			this.stateOptions = [
				{ label: '未审核', value: 1 },
				{ label: '已审核', value: 3 },
			]
		} else {
			this.stateOptions = [
				{ label: '已保存', value: 0 },
				{ label: '已提交', value: 1 },
				{ label: '已退回', value: 2 },
				{ label: '已审核', value: 3 },
			]
		}
		this.gridOptions = Object.assign({
			pinnedBottomRowData: this.createData(1, 'Bottom'),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
				if (params.data.isMsExist == "1") {
					return { 'color': 'red' }
				}
			},
		}, gridOptions())
		this.columnDefs = [
			{
				headerName: "公司",
				field: "companyName",
				width: 200,
				checkboxSelection: true
			},
			{ headerName: "供应商", field: "supplierName", width: 200 },
			{ headerName: "订单号", field: "purOrdNo", width: 100 },
			{ headerName: "行号", field: "purOrdMxNo", width: 80 },
			{ headerName: "物料号", field: "matCode", width: 100 },
			{ headerName: "物料描述", field: "matName", width: 140 },
			{ headerName: "订单数量", field: "orderAmount", width: 120 },
			{ headerName: "已生成数量", field: "genCodeAmount", width: 120 },
			{
				headerName: "类型",
				field: "type",
				width: 70,
				cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">大码</span>'
					else if (params.value == "2")
						return '<span class="ag-icon">小码</span>'
				}
			},
			{ headerName: "申请数量", field: "amount", width: 120 },
			{ headerName: "单位", field: "unit", width: 70 },
			{ headerName: "原因", field: "remark", width: 140 },
			{
				headerName: "申请日期",
				width: 120,
				field: "createDate",
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(params.value).Format("yyyy-MM-dd");
					}
				}
			},
			{
				headerName: "审核日期",
				field: "auditDate",
				width: 120,
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(params.value).Format("yyyy-MM-dd");
					}
				}
			},
		]
		this.getAuthCompany()
	}
}
</script>

<style lang="less">
.m-view-overCodeApply {
	.m-condition {
		.el-form {
			.el-form-item {
				margin-bottom: 0;
			}
		}
	}
	.m-floatright {
		float: right;
	}
}
</style>